package com.imut.lagain.service.impl;

import com.imut.lagain.util.FileUtil;
import com.imut.lagain.constant.AppConstants;
import com.imut.lagain.service.ICacheService;
import com.imut.lagain.service.IFileStorageService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 文件存储服务实现类
 * 处理文件上传、下载、管理等功能
 */
@Service
public class FileStorageServiceImpl implements IFileStorageService {
    private static final Logger log = LoggerFactory.getLogger(FileStorageServiceImpl.class);

    
    private final FileUtil fileUtil;
    
    @Autowired(required = false)
    private ICacheService cacheService;
    
    public FileStorageServiceImpl(FileUtil fileUtil) {
        this.fileUtil = fileUtil;
    }
    
    @Value("${file.upload.path:/uploads}")
    private String uploadPath;
    
    @Value("${file.upload.max-size:10485760}") // 10MB
    private long maxFileSize;
    
    @Value("${file.upload.temp-path:/temp}")
    private String tempPath;
    
    @Value("${file.backup.path:/backup}")
    private String backupPath;

    /**
     * 上传单个文件
     * @param file 文件
     * @param userId 用户ID
     * @param category 文件分类
     * @return 文件信息
     */
    @Override
    public Map<String, Object> uploadFile(MultipartFile file, Long userId, String category) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            validateFile(file);
            String relativePath = generateFilePath(file, userId, category);
            String absolutePath = Paths.get(uploadPath, relativePath).toString();
            createDirectories(Paths.get(absolutePath).getParent());
            file.transferTo(new File(absolutePath));
            result.put("success", true);
            result.put("fileName", file.getOriginalFilename());
            result.put("filePath", relativePath);
            result.put("fileSize", file.getSize());
            result.put("fileType", getFileType(file));
            result.put("uploadTime", LocalDateTime.now());
            result.put("url", "/api/files/" + relativePath);
            cacheFileInfo(relativePath, result);
            updateUserStorageStats(userId, file.getSize(), 1);
            
            log.info("文件上传成功: userId={}, fileName={}, size={}", userId, file.getOriginalFilename(), file.getSize());
            
        } catch (Exception e) {
            log.error("文件上传失败: userId={}, fileName={}", userId, file.getOriginalFilename(), e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 批量上传文件
     * @param files 文件列表
     * @param userId 用户ID
     * @param category 文件分类
     * @return 上传结果列表
     */
    @Async
    @Override
    public CompletableFuture<List<Map<String, Object>>> uploadFiles(List<MultipartFile> files, Long userId, String category) {
        return CompletableFuture.supplyAsync(() -> {
            List<Map<String, Object>> results = new ArrayList<>();
            
            for (MultipartFile file : files) {
                try {
                    Map<String, Object> result = uploadFile(file, userId, category);
                    results.add(result);
                    Thread.sleep(100);
                    
                } catch (Exception e) {
                    log.error("批量上传文件失败: fileName={}", file.getOriginalFilename(), e);
                    Map<String, Object> errorResult = new HashMap<>();
                    errorResult.put("success", false);
                    errorResult.put("fileName", file.getOriginalFilename());
                    errorResult.put("error", e.getMessage());
                    results.add(errorResult);
                }
            }
            
            log.info("批量文件上传完成: userId={}, 总数={}, 成功={}", 
                userId, files.size(), results.stream().mapToInt(r -> (Boolean) r.get("success") ? 1 : 0).sum());
            
            return results;
        });
    }
    
    /**
     * 上传临时文件
     * @param file 文件
     * @param userId 用户ID
     * @return 临时文件信息
     */
    @Override
    public Map<String, Object> uploadTempFile(MultipartFile file, Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            validateFile(file);
            String tempFileName = generateTempFileName(file, userId);
            String tempFilePath = Paths.get(tempPath, tempFileName).toString();
            createDirectories(Paths.get(tempPath));
            file.transferTo(new File(tempFilePath));
            String tempKey = "temp:file:" + tempFileName;
            Map<String, Object> tempInfo = new HashMap<>();
            tempInfo.put("fileName", file.getOriginalFilename());
            tempInfo.put("filePath", tempFileName);
            tempInfo.put("fileSize", file.getSize());
            tempInfo.put("userId", userId);
            tempInfo.put("uploadTime", LocalDateTime.now());
            
            if (cacheService != null) {
                cacheService.setEx(tempKey, tempInfo, 86400); // 24小时过期
            }
            
            result.put("success", true);
            result.put("tempId", tempFileName);
            result.put("fileName", file.getOriginalFilename());
            result.put("fileSize", file.getSize());
            result.put("expireTime", LocalDateTime.now().plusDays(1));
        } catch (Exception e) {
            log.error("临时文件上传失败: userId={}, fileName={}", userId, file.getOriginalFilename(), e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 确认临时文件（将临时文件转为正式文件）
     * @param tempId 临时文件ID
     * @param userId 用户ID
     * @param category 文件分类
     * @return 确认结果
     */
    @Override
    public Map<String, Object> confirmTempFile(String tempId, Long userId, String category) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String tempKey = "temp:file:" + tempId;
            Object tempInfoObj = null;
            if (cacheService != null) {
                tempInfoObj = cacheService.get(tempKey);
            }
            
            if (tempInfoObj == null) {
                throw new RuntimeException("临时文件不存在或已过期");
            }
            
            @SuppressWarnings("unchecked")
            Map<String, Object> tempInfo = (Map<String, Object>) tempInfoObj;
            if (!userId.equals(tempInfo.get("userId"))) {
                throw new RuntimeException("无权限操作此文件");
            }
            String tempFilePath = Paths.get(tempPath, tempId).toString();
            String fileName = (String) tempInfo.get("fileName");
            String relativePath = generateFilePathByName(fileName, userId, category);
            String absolutePath = Paths.get(uploadPath, relativePath).toString();
            createDirectories(Paths.get(absolutePath).getParent());
            Files.move(Paths.get(tempFilePath), Paths.get(absolutePath), StandardCopyOption.REPLACE_EXISTING);
            result.put("success", true);
            result.put("fileName", fileName);
            result.put("filePath", relativePath);
            result.put("fileSize", tempInfo.get("fileSize"));
            result.put("url", "/api/files/" + relativePath);
            cacheFileInfo(relativePath, result);
            if (cacheService != null) {
                cacheService.delete(tempKey);
            }
            updateUserStorageStats(userId, (Long) tempInfo.get("fileSize"), 1);
        } catch (Exception e) {
            log.error("临时文件确认失败: userId={}, tempId={}", userId, tempId, e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取文件输入流
     * @param filePath 文件路径
     * @return 文件输入流
     */
    @Override
    public InputStream getFileInputStream(String filePath) throws IOException {
        String absolutePath = Paths.get(uploadPath, filePath).toString();
        File file = new File(absolutePath);
        
        if (!file.exists()) {
            throw new FileNotFoundException("文件不存在: " + filePath);
        }
        
        return new FileInputStream(file);
    }
    
    /**
     * 获取文件信息
     * @param filePath 文件路径
     * @return 文件信息
     */
    @Override
    public Map<String, Object> getFileInfo(String filePath) {
        try {
            String cacheKey = "file:info:" + filePath;
            Object cachedInfo = null;
            if (cacheService != null) {
                cachedInfo = cacheService.get(cacheKey);
            }
            if (cachedInfo != null) {
                return (Map<String, Object>) cachedInfo;
            }
            String absolutePath = Paths.get(uploadPath, filePath).toString();
            File file = new File(absolutePath);
            
            if (!file.exists()) {
                throw new FileNotFoundException("文件不存在: " + filePath);
            }
            
            Map<String, Object> fileInfo = new HashMap<>();
            fileInfo.put("fileName", file.getName());
            fileInfo.put("filePath", filePath);
            fileInfo.put("fileSize", file.length());
            fileInfo.put("lastModified", new Date(file.lastModified()));
            fileInfo.put("canRead", file.canRead());
            fileInfo.put("canWrite", file.canWrite());
            fileInfo.put("url", "/api/files/" + filePath);
            if (cacheService != null) {
                cacheService.setEx(cacheKey, fileInfo, 3600); // 1小时过期
            }
            
            return fileInfo;
            
        } catch (Exception e) {
            log.error("获取文件信息失败: filePath={}", filePath, e);
            throw new RuntimeException("获取文件信息失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查文件是否存在
     * @param filePath 文件路径
     * @return 是否存在
     */
    @Override
    public boolean fileExists(String filePath) {
        try {
            String absolutePath = Paths.get(uploadPath, filePath).toString();
            return Files.exists(Paths.get(absolutePath));
        } catch (Exception e) {
            log.error("检查文件存在性失败: filePath={}", filePath, e);
            return false;
        }
    }

    /**
     * 删除文件
     * @param filePath 文件路径
     * @param userId 用户ID（用于权限验证）
     * @return 是否成功
     */
    @Override
    public boolean deleteFile(String filePath, Long userId) {
        try {
            if (!isUserFile(filePath, userId)) {
                log.warn("用户无权限删除文件: userId={}, filePath={}", userId, filePath);
                return false;
            }
            
            String absolutePath = Paths.get(uploadPath, filePath).toString();
            File file = new File(absolutePath);
            
            if (!file.exists()) {
                log.warn("要删除的文件不存在: filePath={}", filePath);
                return true; // 文件不存在也算删除成功
            }
            
            long fileSize = file.length();
            boolean deleted = file.delete();
            
            if (deleted) {
                if (cacheService != null) {
                    String cacheKey = "file:info:" + filePath;
                    cacheService.delete(cacheKey);
                }
                updateUserStorageStats(userId, -fileSize, -1);
            } else {
                log.error("文件删除失败: userId={}, filePath={}", userId, filePath);
            }
            
            return deleted;
            
        } catch (Exception e) {
            log.error("删除文件失败: userId={}, filePath={}", userId, filePath, e);
            return false;
        }
    }
    
    /**
     * 批量删除文件
     * @param filePaths 文件路径列表
     * @param userId 用户ID
     * @return 删除结果
     */
    @Async
    @Override
    public CompletableFuture<Map<String, Object>> deleteFiles(List<String> filePaths, Long userId) {
        return CompletableFuture.supplyAsync(() -> {
            Map<String, Object> result = new HashMap<>();
            int successCount = 0;
            int failedCount = 0;
            List<String> failedFiles = new ArrayList<>();
            
            for (String filePath : filePaths) {
                try {
                    if (deleteFile(filePath, userId)) {
                        successCount++;
                    } else {
                        failedCount++;
                        failedFiles.add(filePath);
                    }
                } catch (Exception e) {
                    failedCount++;
                    failedFiles.add(filePath);
                    log.error("批量删除文件失败: filePath={}", filePath, e);
                }
            }
            
            result.put("total", filePaths.size());
            result.put("success", successCount);
            result.put("failed", failedCount);
            result.put("failedFiles", failedFiles);
            
            log.info("批量文件删除完成: userId={}, 总数={}, 成功={}, 失败={}", 
                userId, filePaths.size(), successCount, failedCount);
            
            return result;
        });
    }
    
    /**
     * 移动文件
     * @param sourcePath 源路径
     * @param targetPath 目标路径
     * @param userId 用户ID
     * @return 是否成功
     */
    @Override
    public boolean moveFile(String sourcePath, String targetPath, Long userId) {
        try {
            if (!isUserFile(sourcePath, userId)) {
                log.warn("用户无权限移动文件: userId={}, sourcePath={}", userId, sourcePath);
                return false;
            }
            
            String sourceAbsolutePath = Paths.get(uploadPath, sourcePath).toString();
            String targetAbsolutePath = Paths.get(uploadPath, targetPath).toString();
            createDirectories(Paths.get(targetAbsolutePath).getParent());
            Files.move(Paths.get(sourceAbsolutePath), Paths.get(targetAbsolutePath), StandardCopyOption.REPLACE_EXISTING);
            String sourceCacheKey = "file:info:" + sourcePath;
            String targetCacheKey = "file:info:" + targetPath;
            Object fileInfo = null;
            if (cacheService != null) {
                fileInfo = cacheService.get(sourceCacheKey);
                if (fileInfo != null) {
                    cacheService.delete(sourceCacheKey);
                    cacheService.setEx(targetCacheKey, fileInfo, 3600);
                }
            }
            return true;
            
        } catch (Exception e) {
            log.error("移动文件失败: userId={}, from={}, to={}", userId, sourcePath, targetPath, e);
            return false;
        }
    }
    
    /**
     * 复制文件
     * @param sourcePath 源路径
     * @param targetPath 目标路径
     * @param userId 用户ID
     * @return 是否成功
     */
    @Override
    public boolean copyFile(String sourcePath, String targetPath, Long userId) {
        try {
            if (!isUserFile(sourcePath, userId)) {
                log.warn("用户无权限复制文件: userId={}, sourcePath={}", userId, sourcePath);
                return false;
            }
            
            String sourceAbsolutePath = Paths.get(uploadPath, sourcePath).toString();
            String targetAbsolutePath = Paths.get(uploadPath, targetPath).toString();
            createDirectories(Paths.get(targetAbsolutePath).getParent());
            Files.copy(Paths.get(sourceAbsolutePath), Paths.get(targetAbsolutePath), StandardCopyOption.REPLACE_EXISTING);
            File targetFile = new File(targetAbsolutePath);
            updateUserStorageStats(userId, targetFile.length(), 1);
            return true;
            
        } catch (Exception e) {
            log.error("复制文件失败: userId={}, from={}, to={}", userId, sourcePath, targetPath, e);
            return false;
        }
    }

    /**
     * 清理临时文件
     */
    @Async
    @Override
    public CompletableFuture<Integer> cleanTempFiles() {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Path tempDir = Paths.get(tempPath);
                if (!Files.exists(tempDir)) {
                    return 0;
                }
                
                int cleanedCount = 0;
                LocalDateTime expireTime = LocalDateTime.now().minusDays(1); // 1天前的文件
                
                try (Stream<Path> files = Files.walk(tempDir)) {
                    List<Path> expiredFiles = files
                        .filter(Files::isRegularFile)
                        .filter(path -> {
                            try {
                                return Files.getLastModifiedTime(path).toInstant()
                                    .isBefore(expireTime.atZone(java.time.ZoneId.systemDefault()).toInstant());
                            } catch (IOException e) {
                                return false;
                            }
                        })
                        .collect(Collectors.toList());
                    
                    for (Path file : expiredFiles) {
                        try {
                            Files.delete(file);
                            cleanedCount++;
                            log.debug("清理临时文件: {}", file.getFileName());
                        } catch (IOException e) {
                            log.error("删除临时文件失败: {}", file.getFileName(), e);
                        }
                    }
                }
                return cleanedCount;
                
            } catch (Exception e) {
                log.error("清理临时文件失败", e);
                return 0;
            }
        });
    }
    
    /**
     * 清理过期缓存的文件信息
     */
    @Override
    public void cleanExpiredFileCache() {
        try {
            log.debug("清理过期文件缓存");
        } catch (Exception e) {
            log.error("清理过期文件缓存失败", e);
        }
    }

    /**
     * 获取用户存储统计
     * @param userId 用户ID
     * @return 存储统计
     */
    @Override
    public Map<String, Object> getUserStorageStats(Long userId) {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            String statsKey = "user:storage:" + userId;
            Object cachedStats = null;
            if (cacheService != null) {
                cachedStats = cacheService.hGetAll(statsKey);
            }
            
            if (cachedStats != null && !((Map<?, ?>) cachedStats).isEmpty()) {
                stats = (Map<String, Object>) cachedStats;
            } else {
                stats = calculateUserStorageStats(userId);
                if (cacheService != null) {
                    cacheService.hMSet(statsKey, stats);
                    cacheService.expire(statsKey, 3600, TimeUnit.SECONDS); // 1小时过期
                }
            }
            
        } catch (Exception e) {
            log.error("获取用户存储统计失败: userId={}", userId, e);
            stats.put("error", e.getMessage());
        }
        
        return stats;
    }
    
    /**
     * 获取系统存储统计
     * @return 系统存储统计
     */
    @Override
    public Map<String, Object> getSystemStorageStats() {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            String statsKey = "system:storage:stats";
            Object cachedStats = null;
            if (cacheService != null) {
                cachedStats = cacheService.hGetAll(statsKey);
            }
            
            if (cachedStats != null && !((Map<?, ?>) cachedStats).isEmpty()) {
                stats = (Map<String, Object>) cachedStats;
            } else {
                stats = calculateSystemStorageStats();
                if (cacheService != null) {
                    cacheService.hMSet(statsKey, stats);
                    cacheService.expire(statsKey, 1800, TimeUnit.SECONDS); // 30分钟过期
                }
            }
            
        } catch (Exception e) {
            log.error("获取系统存储统计失败", e);
            stats.put("error", e.getMessage());
        }
        
        return stats;
    }

    /**
     * 验证文件
     */
    private void validateFile(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        
        if (file.getSize() > maxFileSize) {
            throw new IllegalArgumentException("文件大小超过限制: " + maxFileSize + " bytes");
        }
        
        String fileName = file.getOriginalFilename();
        if (fileName == null || fileName.trim().isEmpty()) {
            throw new IllegalArgumentException("文件名不能为空");
        }
        if (!fileUtil.isValidFileType(fileName)) {
            throw new IllegalArgumentException("不支持的文件类型");
        }
    }
    
    /**
     * 生成文件路径
     */
    private String generateFilePath(MultipartFile file, Long userId, String category) {
        String fileName = fileUtil.generateFileName(file.getOriginalFilename());
        String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        return String.format("%s/%s/%s/%s", userId, category, datePath, fileName);
    }
    
    /**
     * 根据文件名生成文件路径
     */
    private String generateFilePathByName(String fileName, Long userId, String category) {
        String newFileName = fileUtil.generateFileName(fileName);
        String datePath = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
        return String.format("%s/%s/%s/%s", userId, category, datePath, newFileName);
    }
    
    /**
     * 生成临时文件名
     */
    private String generateTempFileName(MultipartFile file, Long userId) {
        String extension = fileUtil.getFileExtension(file.getOriginalFilename());
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = UUID.randomUUID().toString().substring(0, 8);
        return String.format("temp_%s_%s_%s.%s", userId, timestamp, random, extension);
    }
    
    /**
     * 获取文件类型
     */
    private String getFileType(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (fileName == null) {
            return "unknown";
        }
        
        String extension = fileUtil.getFileExtension(fileName).toLowerCase();
        String extensionWithoutDot = extension.startsWith(".") ? extension.substring(1) : extension;
        
        for (String imageExt : AppConstants.SUPPORTED_IMAGE_FORMATS) {
            if (imageExt.equalsIgnoreCase(extensionWithoutDot)) {
                return "image";
            }
        }
        
        for (String audioExt : AppConstants.SUPPORTED_AUDIO_FORMATS) {
            if (audioExt.equalsIgnoreCase(extensionWithoutDot)) {
                return "audio";
            }
        }
        
        for (String videoExt : AppConstants.SUPPORTED_VIDEO_FORMATS) {
            if (videoExt.equalsIgnoreCase(extensionWithoutDot)) {
                return "video";
            }
        }
        
        for (String docExt : AppConstants.SUPPORTED_DOCUMENT_FORMATS) {
            if (docExt.equalsIgnoreCase(extensionWithoutDot)) {
                return "document";
            }
        }
        
        return "other";
    }
    
    /**
     * 创建目录
     */
    private void createDirectories(Path path) throws IOException {
        if (path != null && !Files.exists(path)) {
            Files.createDirectories(path);
        }
    }
    
    /**
     * 缓存文件信息
     */
    private void cacheFileInfo(String filePath, Map<String, Object> fileInfo) {
        try {
            if (cacheService != null) {
                String cacheKey = "file:info:" + filePath;
                cacheService.setEx(cacheKey, fileInfo, 3600); // 1小时过期
            }
        } catch (Exception e) {
            log.error("缓存文件信息失败: filePath={}", filePath, e);
        }
    }
    
    /**
     * 更新用户存储统计
     */
    private void updateUserStorageStats(Long userId, long sizeChange, int countChange) {
        try {
            if (cacheService != null) {
                String statsKey = "user:storage:" + userId;
                Map<String, Object> stats = new HashMap<>();
                stats.put("lastUpdate", LocalDateTime.now());
                stats.put("sizeChange", sizeChange);
                stats.put("countChange", countChange);
                cacheService.setEx(statsKey, stats, 3600); // 1小时过期
            }
        } catch (Exception e) {
            log.error("更新用户存储统计失败: userId={}", userId, e);
        }
    }
    
    /**
     * 检查文件是否属于用户
     */
    private boolean isUserFile(String filePath, Long userId) {
        return filePath.startsWith(userId.toString() + "/");
    }
    
    /**
     * 计算用户存储统计
     */
    private Map<String, Object> calculateUserStorageStats(Long userId) {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            String userDir = Paths.get(uploadPath, userId.toString()).toString();
            Path userPath = Paths.get(userDir);
            
            if (!Files.exists(userPath)) {
                stats.put("totalSize", 0L);
                stats.put("fileCount", 0L);
                return stats;
            }
            
            long totalSize = 0;
            long fileCount = 0;
            
            try (Stream<Path> files = Files.walk(userPath)) {
                for (Path file : files.filter(Files::isRegularFile).collect(Collectors.toList())) {
                    totalSize += Files.size(file);
                    fileCount++;
                }
            }
            
            stats.put("totalSize", totalSize);
            stats.put("fileCount", fileCount);
            stats.put("lastCalculated", LocalDateTime.now());
            
        } catch (Exception e) {
            log.error("计算用户存储统计失败: userId={}", userId, e);
            stats.put("totalSize", 0L);
            stats.put("fileCount", 0L);
            stats.put("error", e.getMessage());
        }
        
        return stats;
    }
    
    /**
     * 计算系统存储统计
     */
    private Map<String, Object> calculateSystemStorageStats() {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            Path uploadDir = Paths.get(uploadPath);
            
            if (!Files.exists(uploadDir)) {
                stats.put("totalSize", 0L);
                stats.put("fileCount", 0L);
                stats.put("userCount", 0L);
                return stats;
            }
            
            long totalSize = 0;
            long fileCount = 0;
            long userCount = 0;
            
            try (Stream<Path> userDirs = Files.list(uploadDir)) {
                for (Path userDir : userDirs.filter(Files::isDirectory).collect(Collectors.toList())) {
                    userCount++;
                    
                    try (Stream<Path> files = Files.walk(userDir)) {
                        for (Path file : files.filter(Files::isRegularFile).collect(Collectors.toList())) {
                            totalSize += Files.size(file);
                            fileCount++;
                        }
                    }
                }
            }
            
            stats.put("totalSize", totalSize);
            stats.put("fileCount", fileCount);
            stats.put("userCount", userCount);
            stats.put("lastCalculated", LocalDateTime.now());
            
        } catch (Exception e) {
            log.error("计算系统存储统计失败", e);
            stats.put("totalSize", 0L);
            stats.put("fileCount", 0L);
            stats.put("userCount", 0L);
            stats.put("error", e.getMessage());
        }
        
        return stats;
    }
}